# -*- coding: utf-8 -*-
"""
Created on Fri Dec 14 13:17:46 2012

@author: daniel
"""
import sys
sys.path.append('../optimizers')     
import ga
import flap_geom as fg
import ga2
from numpy import array,max,hstack
import matplotlib.pyplot as plt

def costFcn(x,params):
    g=array([])
    
    af = fg.Airfoil()
    af.read_txt('GA37A315mod_reworked.txt')
    flapRatio = 0.3 
    defl      = 35
    lipLen = x[0]
    leRad = x[1]
    gap = x[2]
    overlap = x[3]
    vratio1 = x[4]
    vratio2 = x[5]
    vratio3 = x[6]
    try:
        Flap  = fg.flap_geometry(af,flapRatio,lipLen, leRad, gap, overlap, defl,vratio1,vratio2,vratio3)
        polar = fg.calc_Jpolar(0.06,3e6,Flap)
        clmax = max(polar.cl)
        f = -clmax
    except:
        f = 100
    return (f,g)
    
def runOpt():
    # X2 = GAP X3 = OVERLAP
#    lb = [0.1,  0.05, 0.005,-0.03,0.5, 1.05,0.2]
    lb = [0.03, 0.1, 0.03, 0.1, 0.005, -0.03]
    ub = [0.20, 0.4, 0.20, 0.8, 0.030,  0.03]
    GA=ga.ga(fg.flap_geometry2,lb,ub,nCPU=1,displayFlag=1)
    GA.maxIter=5
    GA=ga.ga(costFcn,lb,ub,0,8)
    GA.Nelite=4
    GA.maxIter=1000
    GA.maxLagIter=50
    GA.populationSize=30
    GA.solve()

def flapOpt2():
    lb = array([0.10, 0.1, 0.03, 0.1, 0.005, -0.04])
    ub = array([0.20, 0.4, 0.10, 0.8, 0.030,  0.04])
    
    opt = ga2.gaOptions(lb,ub)
    opt.CorrNan = True
    opt.PopSize = 100
    opt.MaxIterations(300,150)
    opt.sigmaEnd = .2
    opt.sigma = 0.8
    opt.MutRate = 0.3
    opt.EliteRatio = 0.1
    opt.HistFile = 'flap_history_03.txt'
    fBest,xBest,fHist,xHist,Iter = ga2.gaMain(fg.flap_objective2, opt)
    optFlap = fg.flap_geometry2(xBest)
    fg.write_txt(optFlap,'flap_result_03.txt')

def generate_igs_files():
    import miscTools as mt
    xOpt = array([0.136949,0.196987,0.067111,0.166011,0.006532,0.035718])
    gap = array([0.5,2.5]) / 100.0
    overlap = array([-2.0,2.0]) / 100.0
    doe = array([[-1,1.],[0,1],[1,1],[-1,0],[0,0],[1,0],[1,-1]])
    doe = (doe + 1.0) / 2.0

    lb = array([gap[0],overlap[0]])
    ub = array([gap[1],overlap[1]])
    xDenorm = array([mt.denormalize(xx,lb,ub) for xx in doe])
    i = 0
    for x in xDenorm:
        i += 1
        xdoe = hstack([xOpt[:-2],x])
        print xdoe
        fg.save_javafoil_igs(xdoe,i)


if __name__=="__main__":
    flapOpt2()